/*
 * 创建人：王曙光
 * 创建时间：2011-9-10
 * 功能描述：文件下载页面功能逻辑
 */
$(function() {	
	
	//启用拖拽
	Common.DragStart($(".download_header")[0]);

	//关闭	
	$(".download_header .close").bind("click", function(event) {
		event.stopPropagation();
		var loginWindow = air.NativeApplication.nativeApplication.openedWindows;
		//window.nativeWindow.close();
		for(var i = 0; i < loginWindow.length; i++) {
			if(!loginWindow[i].visible) {
				loginWindow[i].visible = true;
			}
		}		
		window.nativeWindow.close();
	});
	//获取父级页面传递过来的数据
	var fileId = window.returnValue.split("$#$")[0];
	var filePath = window.returnValue.split("$#$")[1];
	file = new air.File(air.File.applicationDirectory.resolvePath(filePath).nativePath);
	stream = new air.FileStream();
	stream.open(file, air.FileMode.WRITE);
	Download(fileId, 1);
});
//递归实现文件下载
function Download(fileId, next) {
	App.getFile(fileId, next, function(data) {
		if(data.next == 0) {
			var byteData = new air.ByteArray();
			Base64.decode(data.code, byteData);
			stream.writeBytes(byteData, 0, byteData.length);
			stream.close();
			$(".processBar").css({
				"width" : "100%"
			});
			$(".title").html("文件下载中……100%");
			$(".processBar").html("100%");
			Common.ShowTips("下载完成");
			$(".close").trigger("mouseup");
		} else {
			var byteData = new air.ByteArray();
			Base64.decode(data.code, byteData);
			stream.writeBytes(byteData, 0, byteData.length);
			var proc = parseInt(Math.round(next) * 100 / Math.round(data.length));
			$(".processBar").css({
				"width" : proc.toString() + "%"
			});
			$(".processBar").html(proc.toString() + "%");
			$(".title").html("文件下载中……" + proc.toString() + "%");
			Download(fileId, data.next);
		}
	}, function(err) {
		stream.close();
		Common.ShowTips(err);
		$(".close").trigger("mouseup");
	});
}